package cloud.lysky.java.on.concurrent.countdownlatch;

import java.util.concurrent.CountDownLatch;
/**
 * @author luoly
 * @describe
 * @date 2023/3/19 13:18
 **/

public class RaceDemo {
    // 参赛选手个数
    private static final int THREAD_COUNT = 8;
    // 模拟裁判信号枪
    private static final CountDownLatch startSignal = new CountDownLatch(1);
    // 模拟参数选手
    private static final CountDownLatch endSignal = new CountDownLatch(THREAD_COUNT);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < THREAD_COUNT; i++) {
            Thread thread = new Thread(new Runner(startSignal, endSignal), "选手-" + i);
            thread.start();
        }

        // 等待裁判员发令枪
        System.out.println("比赛将在3秒后开始...");
        Thread.sleep(3000);
        startSignal.countDown(); // 发令枪响，比赛开始
        System.out.println("比赛开始!");
        endSignal.await(); // 等待所有选手到达终点
        System.out.println("比赛结束.");
    }
}

class Runner implements Runnable {
    private final CountDownLatch startSignal;
    private final CountDownLatch endSignal;

    public Runner(CountDownLatch startSignal, CountDownLatch endSignal) {
        this.startSignal = startSignal;
        this.endSignal = endSignal;
    }

    @Override
    public void run() {
        try {
            // 等待发令枪响
            startSignal.await();
            Thread.sleep((long) (Math.random() * 10000)); // 模拟跑步时间
            System.out.println(Thread.currentThread().getName() + " 到达终点.");
            endSignal.countDown(); // 完成比赛，计数器减 1
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
